#pragma once
#include <iostream>
#include <string>
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<cstring>

#define PATH "."
#define FIFO_NAME "fifo"
class NameFifo
{
public:
    NameFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path + '/' + _name;
        umask(0);
        // 创建管道文件
        int n = mkfifo(_fifoname.c_str(), O_CREAT | 0666);
        if (n != 0)
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        else
        {
            std::cout << "mkfifo success" << std::endl;
        }
    }

    ~NameFifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            std::cout << "unlink success" << std::endl;
        }
        else
        {
            std::cerr << "unlink error" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
    public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + '/' + _name;
    }
    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void Write()
    {
        std::string message;
        int cnt = 1;
        pid_t id = getpid();
        while (true)
        {
            // 发送数据
            std::cout << "please enter# ";
            std::getline(std::cin, message);
            message += ",message number:" + std::to_string(cnt++) + ",pid:" + std::to_string(id);
            write(_fd, message.c_str(), message.size());
        }
    }
    void Read()
    {
        char buf[1024];
        while (true)
        {
            memset(buf, 0, sizeof(buf));
            // 读取数据
            int n = read(_fd, buf, sizeof(buf) - 1);
            if (n > 0)
            {
                buf[n] = '\0';
                std::cout << "client say#" << buf << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "client quit! me too!" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read error!" << std::endl;
            }
        }
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~FileOper()
    {
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};